package cn.com.godliu.gateway.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 全局过滤器实现了GlobalFilter，这个可以直接注册为bean使用
 * 模拟检测携带accessToken字段，如果没有，拒绝提供服务
 * 全局过滤器是作用在整个网关服务上
 */
@Slf4j
//@Component
public class GlobalFilter implements org.springframework.cloud.gateway.filter.GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());
        log.info("GlobalFilter：{}", time);

        //检测请求 header是否有token传入，如果不符合就返回，实现网关拦截功能
        String accessToken = exchange.getRequest().getHeaders().getFirst("accessToken");
        if (!"abcde".equals(accessToken)) {
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete(); //路由结束，返回给客户端
        }
        return chain.filter(exchange); //继续传递到过滤器列表的下一个
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
